import os
import sys
import threading

from PyQt5.QtCore import Qt, QTimer, QRect
from PyQt5.QtGui import QFont, QPainter, QColor, QIcon  # 添加 QIcon 导入
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,
                             QLabel, QLineEdit, QPushButton)
from pynput.keyboard import Key, Controller
from screeninfo import get_monitors
import time
import pygetwindow as gw

class ActiveWindowTracker:
    def __init__(self):
        self.active_window = None
        self.active_duration = 0
        self._stop_event = threading.Event()
        self._lock = threading.Lock()

    def get_active_window_title(self):
        try:
            return gw.getActiveWindow().title
        except Exception:
            return None

    def _update_active_window(self):
        while not self._stop_event.is_set():
            current_window = self.get_active_window_title()

            with self._lock:
                if current_window != self.active_window:
                    self.active_window = current_window
                    self.active_duration = 0
                else:
                    self.active_duration += 1

            time.sleep(1)

    def start_tracking(self):
        self._stop_event.clear()
        self._tracking_thread = threading.Thread(target=self._update_active_window)
        self._tracking_thread.start()

    def stop_tracking(self):
        self._stop_event.set()
        self._tracking_thread.join()

    def get_active_duration(self):
        with self._lock:
            return self.active_window, self.active_duration

# 激活窗口记录
tracker = ActiveWindowTracker()
tracker.start_tracking()


# ----------------------------
# 窗口管理功能
# ----------------------------
def move_active_window():
    """使用 win+shift+箭头 快捷键移动激活的窗口"""
    print("Moving active window with hotkey")  # 添加调试信息
    # 创建一个键盘控制器
    keyboard = Controller()
    # 按下组合键
    keyboard.press(Key.shift)
    keyboard.press(Key.cmd)  # Windows 键
    keyboard.press(Key.right)

    # 释放组合键
    keyboard.release(Key.right)
    keyboard.release(Key.cmd)
    keyboard.release(Key.shift)


# ----------------------------
# 倒计时悬浮窗
# ----------------------------
class CountdownOverlay(QWidget):
    def __init__(self, monitor):
        super().__init__()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setGeometry(QRect(0, 0, 200, 200))
        self.center(monitor)
        self.countdown = 0
        self.font = QFont("Arial", 72, QFont.Bold)

    def center(self, monitor):
        """居中显示在指定显示器"""
        qr = self.frameGeometry()
        cp = monitor.x + (monitor.width - qr.width()) // 2
        cy = monitor.y + (monitor.height - qr.height()) // 2
        qr.moveTo(cp, cy)
        self.move(qr.topLeft())

    def start(self, seconds):
        """启动倒计时"""
        self.countdown = seconds
        self.show()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_countdown)
        self.timer.start(1000)

    def update_countdown(self):
        """更新倒计时"""
        self.countdown -= 1
        if self.countdown <= 0:
            self.timer.stop()
            self.hide()
        self.update()

    def paintEvent(self, event):
        """绘制倒计时数字"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setFont(self.font)
        painter.setPen(QColor(46, 204, 113, 20))  # 半透明灰色
        painter.drawText(self.rect(), Qt.AlignCenter, str(self.countdown))

# ----------------------------
# 主界面
# ----------------------------
def resource_path(relative_path):
    """ 获取资源文件的绝对路径 """
    try:
        # PyInstaller 创建的临时文件夹
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)


class ScreenSwapper(QWidget):
    def __init__(self):
        super().__init__()
        self.swap_count = 0
        self.total_seconds = 5 * 60  # 默认5分钟
        self.remaining = self.total_seconds
        self.before_window = ''
        self.before_window_duration = 0
        self.overlays = []  # 存储多个倒计时悬浮窗实例
        self.is_always_on_top = False  # 新增变量存储置顶状态
        self.init_ui()

    def init_ui(self):
        # 创建控件
        self.interval_label = QLabel("交换周期（分钟）:")
        self.interval_input = QLineEdit("5")
        self.run_btn = QPushButton("开始运行")
        self.stop_btn = QPushButton("停止运行")
        self.count_label = QLabel("交换次数: 0")
        self.timer_label = QLabel("下次交换剩余: 05:00")
        self.always_on_top_btn = QPushButton("置顶窗口")  # 新增按钮
        self.always_on_top_btn.clicked.connect(self.toggle_always_on_top)  # 连接信号

        # 设置布局
        main_layout = QVBoxLayout()
        row1 = QHBoxLayout()
        row1.addWidget(self.interval_label)
        row1.addWidget(self.interval_input)

        main_layout.addLayout(row1)
        main_layout.addWidget(self.run_btn)
        main_layout.addWidget(self.stop_btn)
        main_layout.addWidget(self.always_on_top_btn)  # 添加按钮到布局
        main_layout.addWidget(self.count_label)
        main_layout.addWidget(self.timer_label)

        # 初始化按钮状态
        self.stop_btn.setEnabled(False)

        # 连接信号
        self.run_btn.clicked.connect(self.start)
        self.stop_btn.clicked.connect(self.stop)

        # 主窗口设置
        self.setLayout(main_layout)
        self.setWindowTitle("双屏内容交换器")
        self.setFixedSize(300, 200)
        self.setWindowIcon(QIcon(resource_path("icon.ico")))  # 设置窗口图标

    def start(self):
        """启动定时器"""
        try:
            minutes = float(self.interval_input.text())
            if minutes <= 0:
                raise ValueError
            self.total_seconds = int(minutes * 60)
            self.remaining = self.total_seconds
            self.run_btn.setEnabled(False)
            self.stop_btn.setEnabled(True)
            self.timer = QTimer(self)
            self.timer.timeout.connect(self.update_timer)
            self.timer.start(1000)  # 每秒更新
            self.update_display()
        except ValueError:
            self.interval_input.setText("5")

    def stop(self):
        """停止定时器"""
        self.timer.stop()
        self.run_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        self.remaining = self.total_seconds
        self.update_display()

    def update_timer(self):
        window, duration = tracker.get_active_duration()
        if self.before_window != '' and self.before_window != window:
            print("窗口发生变化，重置时间:" , window)
            self.before_window = window
            self.before_window_duration = int(duration)
            self.remaining = self.total_seconds

        if self.before_window == '':
            self.before_window = window

        """更新倒计时"""
        self.remaining -= 1

        # 显示3秒倒计时提示
        if self.remaining == 3:
            self.show_overlays(3)

        if self.remaining <= 0:
            print("Timer expired, moving active window")  # 添加调试信息
            move_active_window()  # 使用快捷键移动激活窗口
            self.swap_count += 1
            self.remaining = self.total_seconds
            self.count_label.setText(f"交换次数: {self.swap_count}")

        self.update_display()

    def update_display(self):
        """更新界面显示"""
        mins, secs = divmod(self.remaining, 60)
        self.timer_label.setText(f"下次交换剩余: {mins:02d}:{secs:02d}")

    def show_overlays(self, seconds):
        """在每个显示器上显示倒计时悬浮窗"""
        monitors = get_monitors()
        for monitor in monitors:
            overlay = CountdownOverlay(monitor)
            overlay.start(seconds)
            self.overlays.append(overlay)

    def closeEvent(self, event):
        """关闭所有倒计时悬浮窗"""
        for overlay in self.overlays:
            overlay.close()
        event.accept()

    def toggle_always_on_top(self):
        """切换窗口的置顶状态"""
        self.is_always_on_top = not self.is_always_on_top
        self.setWindowFlag(Qt.WindowStaysOnTopHint, self.is_always_on_top)
        self.show()  # 重新显示窗口以应用新的置顶状态

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ScreenSwapper()
    window.show()
    sys.exit(app.exec_())